<?php

// Submission constants
define ('IN_QUEUE', 0);
define ('COMPILING', 1);
define ('GRADING', 2);
define ('COMPILE_ERROR', 3);
define ('GRADER_ERROR', 4);
define ('FAILED', 5);
define ('PASSED', 6);

class SubmissionObject extends DBObject  {
	public function __construct($id = null) {
		parent::__construct('submissions', array(
  			'status',
  			'time',
			'uid',
			'task',
			'lang',
			'result',
			'score',
			'usage',
			'mem',
			'task_metadata',
			'compile_message'
		), $id, 'sid');
	}
}

class SkillObject extends DBObject {
	public function __construct($name) {
		$model = new SkillModel();
		$skillid = $model->getSkillId($name);
		parent::__construct('skills', array('title', 'handler'), $skillid, 'skillid');
	}
}


$presubmitmap = array(0,
1,
0,
7,
5,
5,
9,
3,
4,
7,
3,
6,
2,
3,
3,0,0,0,0,0,0);

class UserDataObject extends DBObject {
	public $exp, $score;
	public function __construct($id) {
		parent::__construct('user_data', array('exp', 'score', 'num_submit'), $id, 'uid');

			global $conf;
		if (!$this->select($id)) {
			$this->id = $id;
			$this->__set('exp', $conf['start']['exp']);
			$this->__set('score', $conf['start']['score']);
			$this->__set('num_submit', 0);
			
			$db = Database::getDatabase();
            $data = array();
            foreach($this->columns as $k => $v)
                if(!is_null($v))
                    $data[$k] = $db->quote($v);

            $columns = '`' . implode('`, `', array_keys($data)) . '`';
            $values = implode(',', $data);

            $db->query("INSERT INTO `{$this->tableName}` (`uid`, $columns) VALUES (:d, $values)", array('d' => $id));
		}


		
		$sql = 'SELECT exp, score FROM user_tasks WHERE uid=\'' . $id . '\'';
		$db = Database::getDatabase();
		$db->query($sql);
		$rows = $db->getRows();
		$exp = $conf['start']['exp'];
		$score = $conf['start']['score'];
		foreach ($rows as $row) {
			$exp += $row['exp'];
			$score += $row['score'];
		}
		$minus = $this->__get('num_submit');
		$minus *= $minus+1;
		$minus *= 5;
		$minus /= 2;
global $presubmitmap;
$m2 = $presubmitmap[$id];
$m2 *= $m2+1;
		$m2 *= 5;
		$m2 /= 2;
		$this->exp = $exp;
		$this->score = $score-$minus-$m2;
		$this->__set('exp', $exp);
		$this->__set('score', $score);
	}
}

class SkillQueue extends DBObject {
	public function __construct($id = null) {
		parrent::__construct('skill_queue', array('skillid', 'due', 'uid', 'callback'), $id, 'queueid');
	}
}
